/*  This file is part of -_-.

    -_- is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    -_- is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with -_-.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2012-2013 Oliver Katz */

#include "zalloc.h"

unsigned int _zalloc_memusage[Z_ALLOC_MEMORY_CATEGORIES];

void zalloc_init()
{
    memset(_zalloc_memusage, 0, sizeof(_zalloc_memusage));
}

void *zalloc(unsigned int size, unsigned int cat)
{
    void *rtn = malloc(size);
    if (rtn == NULL)
    {
        fprintf(stderr, "ERROR: -_- RAN OUT OF MEMORY\n");
        return NULL;
    }

    if (cat < Z_ALLOC_MEMORY_CATEGORIES)
        _zalloc_memusage[cat] += size;

    return rtn;
}

void zfree(void *ptr)
{
    if (ptr != NULL)
        free(ptr);
}

char *z_strdup(const char *s)
{
    char *rtn = (char *)zalloc(sizeof(char)*strlen(s), Z_ALLOC_DUPLICATION);
    memset(rtn, 0, sizeof(char)*strlen(s));
    strcpy(rtn, s);
    return rtn;
}

char *z_strndup(const char *s, unsigned int size)
{
    char *rtn = (char *)zalloc(sizeof(char)*size, Z_ALLOC_DUPLICATION);
    memset(rtn, 0, sizeof(char)*size);
    strncpy(rtn, s, size);
    return rtn;
}
